package hello.app.util;

import android.app.ProgressDialog;
import android.os.AsyncTask;

public class AdteAsyncTask extends AsyncTask<Object, Void, Object> {

	public interface BackgroundRunner{
		public Object exec(Object ...args);
	}
	public interface FinishRunner{
		public void onFinish(Object result);
	}
	private BackgroundRunner mBackground;
	private FinishRunner mFinish;
	private ProgressDialog mProgressDialog;
	private long mTime = 1000;

	/*
	 * コンストラクタ
	 *
	 * @param activity: 読み出し元Activity
	 */
	public AdteAsyncTask(BackgroundRunner background, FinishRunner finish, ProgressDialog progressDialog) {

		// 呼び出し元のアクティビティを変数へセット
		this.mProgressDialog = progressDialog;
		this.mFinish = finish;
		this.mBackground = background;
		this.mTime = 1000;
	}

	/*
	 * コンストラクタ
	 *
	 * @param activity: 読み出し元Activity
	 */
	public AdteAsyncTask(BackgroundRunner background, FinishRunner finish, ProgressDialog progressDialog, long time) {

		// 呼び出し元のアクティビティを変数へセット
		this.mProgressDialog = progressDialog;
		this.mFinish = finish;
		this.mBackground = background;
	}

	public AdteAsyncTask(){
	}

	public void setBackgroundRunner(BackgroundRunner background){
		mBackground = background;
	}

	public void setPostRunner(FinishRunner finish){
		mFinish = finish;
	}

	public void setDelayTime(long time){
		mTime = time;
	}

	/*
	 * 実行前の事前処理
	 */
	@Override
	protected void onPreExecute() {
		if(mProgressDialog != null){
			this.mProgressDialog.show();
		}
		return;
	}

	/*
	 * バックグラウンドで実行する処理
	 * @param params: Activityから受け渡されるデータ
	 * @return onPostExecute()へ受け渡すデータ
	 */
	@Override
	protected Object doInBackground(Object... params) {
		Object ret = false;
		try {
			Thread.sleep(this.mTime);
			if(mBackground != null){
				ret = mBackground.exec(params);
			}

		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return ret;
	}

	/*
	 * メインスレッドで実行する処理
	 * @param param: doInBackground()から受け渡されるデータ
	 */
	@Override
	protected void onPostExecute(Object result) {
		// プログレスダイアログを閉じる
		if (this.mProgressDialog != null && this.mProgressDialog.isShowing()) {
			this.mProgressDialog.dismiss();
		}
		if(mFinish != null){
			mFinish.onFinish(result);
		}
	}

	@Override
	protected void onCancelled() {
		super.onCancelled();
		if (this.mProgressDialog != null) {
			if (this.mProgressDialog.isShowing()) {
				this.mProgressDialog.dismiss();
			}
		}
		return;
	}

}
